<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from "@/api/search.js";
export default {
  name: "SearchResult",
  components: {},
  props: {
    //父组件传来的要搜索的文本
    value: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [], //存放请求结果列表的数组
      loading: false, //加载状态 false才能继续加载
      finished: false, //是否加载完全 true就是加载完全
      page: 1, //请求页码
      perPage: 10, //每页大小
      error: false, //失败状态
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    //触底加载事件
    async onLoad() {
      // 发起请求
      try {
        const { data } = await getSearchResult({
          page: this.page, //页码
          per_page: this.perPage, //每页大小
          q: this.value, //查询词
        });
        //更新数据
        const { results } = data.data;
        this.list.push(...results);
        // 加载状态结束
        this.loading = false;
        //判断数据是否加载完毕
        if (results.length) {
          this.page++; // 更新获取下一页数据的页码
        } else {
          this.finished = true; // 没有数据了，将加载状态设置结束，不再 onLoad
        }
      } catch (err) {
        //失败就把状态改为true提示错误文本
        this.error = true;
        // 开启加载状态
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped lang="less"></style>
